import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { SearchBar, List, Menu, WhiteSpace } from 'antd-mobile';
import styles from './styles.less';

class FoodListPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOffsetTop: 0,
    };

    const { dispatch, filters } = props;
    if (filters) {
      dispatch({
        type: 'food/clear',
      });
    }
  }

  componentDidMount() {
    const node = findDOMNode(this.refs.menu);
    if (node) {
      this.setState({
        menuOffsetTop: node.offsetTop,
      });
    }
  }

  handleSearchChange(v) {
    if (v.trim()) {
      this.props.dispatch({
        type: 'food/search',
        payload: v,
      });
    }
  }

  handleSearchClear() {
    this.props.dispatch({
      type: 'food/clear',
    });
  }

  showFoodDetail(id) {
    const {
      dispatch,
      location: { pathname },
    } = this.props;

    dispatch(routerRedux.push({
      pathname: `${pathname}/${id}`,
      state: {
        id,
        title: '健康可餐',
      },
    }));
  }

  renderFilters() {
    return (
      <List>
        {this.props.filters.map(filter =>
          <List.Item
            key={filter.id}
            onClick={() => this.showFoodDetail(filter.id)}>
            {filter.name}
          </List.Item>
        )}
      </List>
    );
  }

  renderFoods() {
    const { foods } = this.props;
    return foods.length ? (
      <Menu
        ref="menu"
        className="menu-foods"
        data={foods}
        height={document.documentElement.clientHeight - this.state.menuOffsetTop}
        onChange={(value) => this.showFoodDetail(value[1])} />
    ) : null;
  }

  render() {
    return (
      <div>
        <SearchBar
          placeholder="搜索"
          onChange={(v) => this.handleSearchChange(v)}
          onClear={() => this.handleSearchClear()}/>
        <WhiteSpace />
        {this.props.filters ? this.renderFilters() : this.renderFoods()}
      </div>
    );
  }
}

const mapStateToProps = ({ food: { data, search } }) => ({
  foods: data,
  filters: search,
});

export default connect(mapStateToProps)(FoodListPage);
